package com.dzm.xgb.core.controller.admin;

import com.alibaba.excel.EasyExcel;
import com.dzm.common.exception.BusinessException;
import com.dzm.common.result.R;
import com.dzm.common.result.ResponseEnum;
import com.dzm.xgb.core.pojo.dto.ExcelDictDTO;
import com.dzm.xgb.core.pojo.entity.Dict;
import com.dzm.xgb.core.service.DictService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * 作者：Dzm
 * 时间：2024-08-28-14:36
 * 功能：
 */
@Api(tags = "文件管理")
@RestController
@RequestMapping("/admin/core/dict")
public class AdminDictController {

    @Autowired
    private DictService dictService;

    @ApiOperation("上传Excel文件，并写入数据库")
    @PostMapping("/import")
    public R importExcel(@RequestParam("file") MultipartFile file) throws IOException {
        dictService.importData(file);

        return R.ok();
    }

    @ApiOperation("将数据库中的数据导出到Excel中")
    @GetMapping("/export")
    public void exportExcel(HttpServletResponse response) {
        try {
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");

            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            // String fileName = URLEncoder.encode("mydict", "UTF-8").replaceAll("\\+", "%20");
            String fileName = "test";
            response.setHeader("Content-disposition",  "attachment;filename*=utf-8''" + fileName + ".xlsx");
            EasyExcel.write(response.getOutputStream(), ExcelDictDTO.class).sheet("数据字典").doWrite(dictService.listDictData());
        } catch (IOException e) {
            throw new BusinessException(ResponseEnum.EXPORT_DATA_ERROR);
        }

    }

    @ApiOperation("根据id获取子分类")
    @GetMapping("/getByPid/{pid}")
    public R getByPid(@PathVariable("pid") Integer pid) {
        List<Dict> list = dictService.findChildrenByParentId(pid);

        return R.ok().data("list", list);
    }
}
